const pool = require('../tools/getPool');
const sendResponse = require('../tools/sendResponse');

module.exports = function(req, res){

	let author_id = req.body.id;
	let news_id = req.body.news_id;
	let comment = req.body.comment;

	let params = [author_id, news_id, comment];

	// 获取数据库连接
	pool.getConnection(function(err, connection) {
		if (err) {
			console.log(err);
			sendResponse('error','数据库内部错误', null, res);
			return;
		}

		connection.query('SELECT able FROM user where id = ?', author_id, function(error, rows, fields){
			if (error) {
				sendResponse('error','数据库内部错误', null, res);
				return;
			} else {
				if (rows[0].able == 0 || rows[0].able == "0") {
					sendResponse('error', '该用户已被禁用', null, res);
				} else {
				// 执行语句
					connection.query('INSERT INTO comment (author_id, news_id, content) VALUES (?,?,?);', params, function (error, rows, fields) {
						// 释放连接
						connection.release();

						if (error) { 
							console.log(error);
							sendResponse('error','数据库内部错误', null, res);
							return;
						}

						sendResponse('ok','发表成功', rows, res);

					})	
				}
			}
		})



	});

}